package com.example.train_operate.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.train_operate.dto.*;
import com.example.train_operate.entity.MeetingInfo;
import com.example.train_operate.service.MeetingInfoService;
import com.example.train_operate.mapper.MeetingInfoMapper;
import com.example.train_operate.service.UserService;
import com.example.train_operate.util.*;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.transform.JDOMSource;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.time.ZoneId;

import static com.example.train_operate.constants.UrlConstants.*;
import static com.example.train_operate.constants.YunWuConstants.*;


/**
* @author 21609
* @description 针对表【tb_meeting_info】的数据库操作Service实现
* @createDate 2025-09-20 18:56:45
*/
@Service
@Slf4j
public class MeetingInfoServiceImpl extends ServiceImpl<MeetingInfoMapper, MeetingInfo>
    implements MeetingInfoService{

    @Resource
    private MeetingInfoMapper meetingInfoMapper;

    /**
     * 创建房间(云屋)
     * @return
     */
    @Override
    public Result addMeetingInfo() {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();
        RoomDTO roomDTO = RequestParamSet.setDefaultParam(String.valueOf(userId));
        Gson gson = new Gson();
        String requestBody = gson.toJson(roomDTO);
        OkHttpRequest okHttpRequest = new OkHttpRequest();
        String response = okHttpRequest.sendRequestSync(CREATE_ROOM_URL, "POST", null, requestBody, null);
        if(response == null){
            return Result.fail().message("请求异常！");
        }
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.getInteger(RSP_CODE) != 0) {
            return Result.fail().message(jsonObject.getString(RSP_DESC));
        }
        String dataJson = jsonObject.getString(DATA);
        JSONObject data = JSON.parseObject(dataJson);
        Long roomId = data.getLong(ROOM_ID);
        try{
            MeetingInfo meetingInfo = new MeetingInfo();
            meetingInfo.setMeetingNo(roomId);
            meetingInfo.setCreateUserId(userId);
            meetingInfoMapper.insert(meetingInfo);
            return Result.ok(meetingInfo);
        } catch (Exception e){
            return Result.fail().message("视频通话创建失败！");
        }
    }

    /**
     * 结束房间
     * @param roomId
     * @return
     */
    @Override
    public Result finishMeeting(Long roomId) {
        UserDTO userDTO = UserHolder.getUser();
        Integer userId = userDTO.getId();
        RoomDTO roomDTO = RequestParamSet.setSpecifyParam(String.valueOf(userId), String.valueOf(roomId));
        Gson gson = new Gson();
        String requestBody = gson.toJson(roomDTO);
        OkHttpRequest okHttpRequest = new OkHttpRequest();
        String response = okHttpRequest.sendRequestSync(FINISH_ROOM_URL, "POST", null, requestBody, null);
        if(response == null){
            return Result.fail().message("请求异常！");
        }
        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.getInteger(RSP_CODE) != 0){
            return Result.fail().message(jsonObject.getString(RSP_DESC));
        }
        try{
            QueryWrapper<MeetingInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("meeting_no", roomId);
            MeetingInfo meetingInfo = meetingInfoMapper.selectOne(queryWrapper);
            meetingInfo.setMeetingStatus(1);
            meetingInfoMapper.updateById(meetingInfo);
            return Result.ok().message("视频通话结束成功！");
        } catch (Exception e){
            return Result.fail().message("视频通话结束失败！");
        }
    }

    /**
     * 删除房间
     * @param roomId
     * @return
     */
    @Override
    public Result deleteMeeting(Long roomId) {
        UserDTO userDTO = UserHolder.getUser();
        Integer userId = userDTO.getId();
        RoomDTO roomDTO = RequestParamSet.setSpecifyParam(String.valueOf(userId), String.valueOf(roomId));
        Gson gson = new Gson();
        String requestBody = gson.toJson(roomDTO);
        OkHttpRequest okHttpRequest = new OkHttpRequest();
        String response = okHttpRequest.sendRequestSync(DELETE_ROOM_URL, "POST", null, requestBody, null);
        if(response == null){
            return Result.fail().message("请求异常！");
        }
        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.getInteger(RSP_CODE) != 0){
            return Result.fail().message(jsonObject.getString(RSP_DESC));
        }
        try{
            QueryWrapper<MeetingInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("meeting_no", roomId);
            MeetingInfo meetingInfo = meetingInfoMapper.selectOne(queryWrapper);
            meetingInfo.setIsDelete(1);
            meetingInfoMapper.updateById(meetingInfo);
            return Result.ok().message("视频通话删除成功！");
        } catch (Exception e){
            return Result.fail().message("视频通话删除失败！");
        }
    }

    /**
     * 查询房间在线人数
     * @param roomId
     * @return
     */
    @Override
    public Result selectMeetingOnlineCount(Long roomId) {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();
        OnlineCountDTO onlineCountDTO = RequestParamSet.setOnlineCountParam(String.valueOf(userId), String.valueOf(roomId));
        Gson gson = new Gson();
        String requestBody = gson.toJson(onlineCountDTO);
        OkHttpRequest okHttpRequest = new OkHttpRequest();
        String response = okHttpRequest.sendRequestSync(GET_ONLINE_NUMBER_URL, "POST", null, requestBody, null);
        log.info("response==========>{}", response);
        if(response == null){
            return Result.fail().message("请求异常！");
        }
        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.getInteger(RSP_CODE) != 0){
            return Result.fail().message(jsonObject.getString(RSP_DESC));
        }
        String dataJson = jsonObject.getString(DATA);
        if (dataJson.equals("[]")){
            return Result.fail().message("无在线用户！");
        }
        log.info("dataJson==========>{}", dataJson);
        JSONObject data = JSON.parseObject(dataJson);
        Long userCount = data.getLong(USERS_COUNT);
        return Result.ok(userCount);
    }

    /**
     * 查询房间在线用户信息
     * @param roomId
     * @return
     */
    @Override
    public Result selectOnlineInformation(Long roomId) {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();
        RoomDTO roomDTO = RequestParamSet.setSpecifyParam(String.valueOf(userId), String.valueOf(roomId));
        Gson gson = new Gson();
        String requestBody = gson.toJson(roomDTO);
        OkHttpRequest okHttpRequest = new OkHttpRequest();
        String response = okHttpRequest.sendRequestSync(GET_ONLINE_INFO_URL, "POST", null, requestBody, null);
        if(response == null){
            return Result.fail().message("请求异常！");
        }
        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.getInteger(RSP_CODE) != 0){
            return Result.fail().message(jsonObject.getString(RSP_DESC));
        }
        String dataJson = jsonObject.getString(DATA);
        if(dataJson == null){
            return Result.fail().message("未查询到在线用户信息！");
        }
        JSONObject data = JSON.parseObject(dataJson);
        return Result.ok(data);
    }

    /**
     * 查询历史房间列表
     * @return
     */
    @Override
    public Result selectHistoryMeetings(HistoryMeetingParamDTO historyMeetingParamDTO) {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();
        if(historyMeetingParamDTO.getStartTime() == null || historyMeetingParamDTO.getEndTime() == null){
            return Result.fail().message("请选择时间段！");
        }
        if(historyMeetingParamDTO.getStartTime().isAfter(historyMeetingParamDTO.getEndTime())){
            return Result.fail().message("请选择正确的时间段！");
        }
        HistoryMeetingDTO historyMeetingDTO = RequestParamSet.setHistoryMeetingParam(String.valueOf(userId),
                historyMeetingParamDTO.getRoomId(),
                historyMeetingParamDTO.getStartTime().atZone(ZoneId.systemDefault()).toEpochSecond(),
                historyMeetingParamDTO.getEndTime().atZone(ZoneId.systemDefault()).toEpochSecond(),
                historyMeetingParamDTO.getPageNumber());
        Gson gson = new Gson();
        String requestBody = gson.toJson(historyMeetingDTO);
        OkHttpRequest okHttpRequest = new OkHttpRequest();
        String response = okHttpRequest.sendRequestSync(GET_HISTORY_ROOM_URL, "POST", null, requestBody, null);
        if(response == null){
            return Result.fail().message("请求异常！");
        }
        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.getInteger(RSP_CODE) != 0){
            return Result.fail().message(jsonObject.getString(RSP_DESC));
        }
        String dataJson = jsonObject.getString(DATA);
        if(dataJson == null){
            return Result.fail().message("未查询到历史房间信息！");
        }
        JSONObject data = JSON.parseObject(dataJson);
        return Result.ok(data);
    }


}




